package com.zhang.interceptor;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author zh
 * @create 2022-03-03 17:15
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("X-Token");
        if(token!=null){
            String username = (String) redisTemplate.opsForValue().get(token);
            if(username==null){
                response.setContentType("application/json;charset=utf-8");
                //{msg:"NOLOGIN"}
                response.getWriter().write("{msg:\"NOLOGIN\"}");
                return false;
            }else {
                redisTemplate.opsForValue().set(token,username,30, TimeUnit.MINUTES);
                return true;
            }
        }else {
            return false;
        }
    }
}
